import { Good } from "../../components/goods/goods";
import { ADDRESS, CARTS } from "../../config";
import { Event } from "../../utils/interface";
import { observer } from "../../utils/observer";
import { Detail } from "../goods_detail/goods_detail";

let carts: Array<Detail> = [];
let allPrice = 0;
let allCount = 0;
let flag = false;
let data = {
  carts,
  allPrice,
  allCount,
  flag,
};

Page({
  data,
  onShow() {
    data = observer(this.data, this) as any;
    this.init();
  },
  addAddress,
  init() {
    let carts = wx.getStorageSync(CARTS);
    carts || (carts = []);
    data.carts = carts;
    updateCart(false);
  },
  increment(e: Event<{ id: Detail }>) {
    const id = e.currentTarget.dataset.id;
    const detail = data.carts.find((item) => item.goods_id === +id);
    if (detail && detail.count != undefined && detail.count <= 99) {
      detail.count++;
    }
    updateCart();
  },
  decrement(e: Event<{ id: Detail }>) {
    const id = e.currentTarget.dataset.id;
    const detail = data.carts.find((item) => item.goods_id === +id);
    if (detail && detail.count != undefined && detail.count > 0) {
      detail.count--;
    }
    updateCart();
  },
  submit(e: Event<{ id: Detail }>) {
    const val = +e.detail.value;
    const id = e.currentTarget.dataset.id;
    const detail = data.carts.find((item) => item.goods_id === +id);
    if (detail) {
      detail.count !== undefined && (detail.count = val);
    }
    updateCart();
  },
  changeChe() {
    if (data.flag) {
      data.carts.forEach((item) => {
        item.flag = false;
      });
    } else {
      data.carts.forEach((item) => {
        item.flag = true;
      });
    }
    data.flag = !data.flag;
    updateCart();
  },
  itemChe(e: Event<{ row: Detail }>) {
    const id = e.currentTarget.dataset.row;
    const detail = data.carts.find((item) => item.goods_id === +id);
    detail && (detail.flag = !detail.flag);
    updateCart();
  },
  toDetails,
  toPay() {
    wx.navigateTo({
      url: "/pages/pay/pay",
    });
  },
});

function toDetails(e: Event<{ row: Good }>) {
  wx.navigateTo({
    url: `/pages/goods_detail/goods_detail?goods_id=${e.currentTarget.dataset.row.goods_id}`,
  });
}

function updateCart(falg = true) {
  data.allPrice = data.carts.reduce((pre, item) => {
    return (pre += item.flag ? item.count * item.goods_price : 0);
  }, 0);
  data.allCount = data.carts.reduce((pre, item) => {
    return (pre += item.flag ? item.count : 0);
  }, 0);
  data.flag = data.carts.some((item) => item.flag);
  falg && wx.setStorageSync(CARTS, data.carts);
}
export function addAddress() {
  wx.chooseAddress({
    success(e) {
      const add = wx.getStorageSync(ADDRESS) || [];
      if (add.some((item: any) => item.detailInfo === e.detailInfo)) return;
      add.push(e);
      wx.setStorageSync(ADDRESS, add);
    },
    fail() {
      console.log("ject");
    },
  });
}
